#include <ptgui/ptgui.h>
#include <ptgui/surface.h>

void ptgui_surface_init(ptgui_surface_t *surface, const ptgui_surface_backend_t *backend)
{
	ptgui_rect_t rect;
	surface->backend = backend;

	surface->refs = 1;

	ptgui_graphic_driver_get_default_rect(&rect);

	surface->w = ptgui_rect_width(rect);
	surface->h = ptgui_rect_height(rect);
}

ptgui_surface_t * ptgui_surface_create(void)
{
	ptgui_surface_t *surface;

	surface = PTGUI_TYPE_MALLOC(ptgui_surface_t);
	if (surface == NULL) {
		return NULL;
	}

	ptgui_surface_init(surface, NULL);

	return surface;
}

void ptgui_surface_destroy(ptgui_surface_t *surface)
{
	if (surface == NULL) {
		return;
	}

	surface->refs--;
	if (surface->refs) {
		return;
	}

	ptgui_free(surface);
}

void ptgui_surface_blit(ptgui_surface_t *surface, ptgui_dc_t *dc, ptgui_rect_t *rect)
{
	if (surface->backend->blit != NULL) {
		surface->backend->blit(surface, dc, rect);
	}
}

/******************************************************************************/
/*  																	 */
/******************************************************************************/
void ptgui_surface_image_blit(ptgui_surface_t *surface, ptgui_dc_t *dc, ptgui_rect_t *rect)
{
	ptgui_surface_image_t *self;

	self = (ptgui_surface_image_t *)surface;

	ptgui_image_blit(self->image, dc, rect);
}

const ptgui_surface_backend_t surface_image_backend =
{
	NULL,
	ptgui_surface_image_blit,
};

ptgui_surface_t * ptgui_surface_create_image(ptgui_image_t *image)
{
	ptgui_surface_image_t *surface;

	surface = (ptgui_surface_image_t *)ptgui_malloc(sizeof(ptgui_surface_image_t));
	if (surface == NULL) {
		return NULL;
	}

	ptgui_surface_init(&surface->base, &surface_image_backend);

	surface->image = image;
	surface->base.w = image->w;
	surface->base.h = image->h;

	return (ptgui_surface_t *)surface;
}